package CustomView;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.qb.devtest.R;

import java.io.IOException;

import utils.MyUtil;

public class CustomVideoPlayer extends FrameLayout {
    Context ctx;
    private VideoView vvVideo;
    private Button button;
    private TextView tvName,tvTime;
    private SeekBar seekVideo;
    private Handler handler = new Handler();
    private Runnable updateProgressBarRunnable;
    private Boolean isPlaying = false;
    private Boolean videoIsFull = false;

    public CustomVideoPlayer(Context context) {
        super(context);
        init(context);
    }

    public CustomVideoPlayer(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        ctx = context;
        LayoutInflater inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.custom_video_player, this, true);
        vvVideo = findViewById(R.id.vv_video);
        vvVideo.setOnClickListener(view1 -> {
            if (!isPlaying) return;
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) vvVideo.getLayoutParams();
            if (videoIsFull) {
                layoutParams.width = 400;
                layoutParams.height = 240;
            } else {
                layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
                layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
            }
            vvVideo.setLayoutParams(layoutParams);
            videoIsFull = !videoIsFull;
        });

        button = findViewById(R.id.btn_play);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (vvVideo == null) {
                    Toast.makeText(context, "请先选择视频文件", Toast.LENGTH_SHORT).show();
                } else {
                    if (isPlaying) {
                        vvVideo.pause();
                        isPlaying = false;
                    } else {
                        vvVideo.start();
                        isPlaying = true;
                    }
                    setPlayBtn();
//                    invalidate();
                }

            }
        });

        tvName = findViewById(R.id.tv_video_name);
        tvName.setText("还没加载视频");
        tvTime = findViewById(R.id.tv_video_time);
        tvTime.setText("--/--");
        seekVideo = findViewById(R.id.seek_video);
        seekVideo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 当用户拖动滑块时触发
                if (vvVideo!=null) {
                    int total = vvVideo.getDuration();
                    vvVideo.seekTo(progress);
                    updateTimeShow(progress,total);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 当用户开始拖动滑块时触发
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 当用户停止拖动滑块时触发
            }
        });
    }

    private void setPlayBtn() {
        String text = "播放";
        int icon = R.drawable.ic_baseline_play_arrow_24;
        MyUtil.showLog("setPlayBtn",isPlaying);
        if (isPlaying) {
            text = "暂停";
            icon = R.drawable.ic_baseline_pause_24;
            // 开始计时器更新进度条
            handler.post(updateProgressBarRunnable);
        }
        button.setText(text);
        Drawable drawable = ctx.getResources().getDrawable(icon);
        drawable.setBounds(0, 0, 36,36);
        button.setCompoundDrawables(drawable, null, null, null);
    }

    public void loadVideo(Uri uri) {
        isPlaying = false;
        setPlayBtn();
        // 设置音频文件路径或URI
        try {
            vvVideo.setVideoURI(uri);
            tvName.setText(MyUtil.getFileNameFromUri(ctx,uri));

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(ctx, "视频加载失败，"+e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        // 设置vvVideo的准备状态监听器
        vvVideo.setOnPreparedListener(mp -> {
            // 准备好后可以开始播放
            mp.start();
            isPlaying = true;
            setPlayBtn();
            videoIsFull = false;
            seekVideo.setMax(vvVideo.getDuration());
        });

        // 设置进度条更新逻辑
        updateProgressBarRunnable = new Runnable() {
            @Override
            public void run() {
                int currentPosition = vvVideo.getCurrentPosition();
                int total = vvVideo.getDuration();

                if (total > 0) {
                    seekVideo.setProgress(currentPosition);
                    updateTimeShow(currentPosition,total);
                    MyUtil.showLog("updateProgressBarRunnable",currentPosition+":"+total);
                    if (currentPosition<total - 100) {
                        if (isPlaying) handler.postDelayed(this, 1000);
                    } else {
                        handler.removeCallbacks(this);
                        isPlaying = false;
                        setPlayBtn();
                    }
                }
            }
        };
    }

    private void updateTimeShow(int c,int t) {
        int tm = (int) (t / (1000 * 60));
        int ts = (int) ((t % (1000 * 60)) / 1000);
        int cm = (int) (c / (1000 * 60));
        int cs = (int) ((c % (1000 * 60)) / 1000);
        tvTime.setText(cm+":"+cs+"/"+tm+":"+ts);
    }

    public void stop() {
        if (vvVideo != null) {
            vvVideo.stopPlayback();
            vvVideo = null;
        }
        handler.removeCallbacks(updateProgressBarRunnable);
    }
}
